<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script lang="javascript">
    // 节流
    // 1.时间戳写法，事件会立即执行，停止触发后没有办法再次执行
    function throttled1(fn,delay=500){
      let oldtime = Date.now()
      return function(...args){
        let newtime = Date.now()
        if(newtime-oldtime>=delay){
          fn.apply(null,args)
          oldtime =Date.now()
        }
      }
    }
    // 2.定时器写法，delay毫秒后第一次执行，第二次事件停止触发后依然会再一次执行
    function throttled2(fn,delay=500){
      let timer =null;
      return function(...args){
        if(!timer){
          timer = setTimeout(() => {
            fn.apply(this,args)
            timer=null
          }, delay);
        }
      }
    }

    // 防抖
    // 简单实现
    function debounce(func,wait){
      let timeout;
      return function(){
        let context = this;
        let args = arguments;

        clearTimeout(timeout);
        timeout =setTimeout(function(){
          func.apply(context,args)
        },wait)
      }
    }
  </script>
</body>
</html>